package com.hmc.test;

import org.junit.Assert;
import org.junit.Test;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Random;

import static java.lang.Float.NaN;
import static java.lang.Float.POSITIVE_INFINITY;

/**
 * >>>表示无符号右移
 * 浮点型中NaN和infinity:    NaN表示非数字的数，Infinity表示无穷大
 * 二进制取余运算可以用(n-1)&x 其中n必须为2的幂值
 */
public class HashMapStudy {

    @Test
    public void testFloat() {
        Float [] numbers = {0.0f/0.0f,NaN,-0.1f/0.0f,POSITIVE_INFINITY};
        System.out.println(Arrays.toString(numbers));
    }

    @Test
    //测试使用2进制的好处
    //取模运算（n-1）&x n只能为2的幂值
    public void testByte() {
        Random random = new Random(System.currentTimeMillis());
        int a = -1;
        boolean b;
        for (int i = 0; i < 20; i++) {
            while (a<0)
                a = random.nextInt();
            b = quyu(a, 1 << i);
            System.out.println(a+"\t"+(1<<i));
            Assert.assertEquals(b, true);
        }

    }

    private boolean quyu(int a,int b) {
        int c = a%b;
        int d = a&(b-1);
        return c==d;
    }

    /**
     * 为什么hashMap的最大容量为2的30次方
     * 整形占4个字节，最大值为1<<31-1
     */
    @Test
    public void whyMax() {
        int [] number = {1<<30,1<<31,1<<32};
        printIntArray(number);
    }

    /**
     * 为什么使用异或而不使用与和或
     */
    @Test
    public void test1() {
        System.out.println("异或运算：");
        //异或运算
        int numbers[] = {0^0,0^1,1^0,1^1};
        printIntArray(numbers);

        //与运算
        System.out.println("与运算：");
        int numbers1[] = {0&0,0&1,1&0,1&1};
        printIntArray(numbers1);

        //或运算
        System.out.println("或运算：");
        int numbers2[] = {0|0,0|1,1|0,1|1};
        printIntArray(numbers2);
    }

    static final int MAXIMUM_CAPACITY = 1 << 30;
    /**
     * 返回一个不小于cap的最小2次幂的值
     * @param cap
     * @return
     */
    static final int tableSizeFor(int cap) {
        int n = cap - 1;
        n |= n >>> 1;
        n |= n >>> 2;
        n |= n >>> 4;
        n |= n >>> 8;
        n |= n >>> 16;
        return (n < 0) ? 1 : (n >= MAXIMUM_CAPACITY) ? MAXIMUM_CAPACITY : n + 1;
    }

    @Test
    public void test2(){
        System.out.println(tableSizeFor(15));
    }


    private void printIntArray (int[] numbers) {
        //1.直接遍历数组，一个一个打印
        /*if (numbers != null && numbers.length > 0) {
            for (int number : numbers) {
                System.out.print(number+"\t");
            }
            System.out.println();
        }*/
        //2.使用数组工具类，直接将数组转化为字符串
        String arrarStr = Arrays.toString(numbers);
        System.out.println(arrarStr);
    }
}
